package com.clp.protocol.core.common.connect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.io.Closeable;
import java.util.concurrent.ScheduledExecutorService;

/**
 * 内嵌Netty框架启动相关类
 */
public class NettyClient<I extends ChannelInitializer<SocketChannel>> implements Closeable {
    private final Bootstrap bootstrap;
    private final EventLoopGroup eventLoopGroup;

    public NettyClient() {
        this.bootstrap = new Bootstrap();
        this.eventLoopGroup = new NioEventLoopGroup();
        bootstrap.group(eventLoopGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true);
    }

    public ScheduledExecutorService scheduledExecutor() {
        return eventLoopGroup;
    }

    public ChannelFuture connect(I aInitializer, String remoteHost, int remotePort) {
        if (aInitializer == null) throw new NullPointerException("The initializer is null");
        synchronized (bootstrap) {
            return bootstrap.handler(aInitializer).connect(remoteHost, remotePort);
        }
    }

    public ChannelFuture connect(I aInitializer, String localHost, int localPort, String remoteHost, int remotePort) {
        if (aInitializer == null) throw new NullPointerException("The initializer is null");
        synchronized (bootstrap) {
            return bootstrap.handler(aInitializer).localAddress(localHost, localPort).connect(remoteHost, remotePort);
        }
    }

    public boolean isClosed() {
        return eventLoopGroup.isShutdown();
    }

    /**
     * 关闭客户端
     */
    @Override
    public void close() {
        // 停止BootStrap
        if (!eventLoopGroup.isShutdown()) {
            eventLoopGroup.shutdownGracefully();
        }
    }
}
